package com.elinkway.infinitemovies.bigdata;

import android.content.Context;
import android.text.TextUtils;

import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;

public class BigDataStats {
    public static boolean DEBUG = false;
    private static Context globalcontext;
    private static BigDataThread mThread;

    public static void setDebug(boolean debug) {
        DEBUG = debug;
    }

    public static void init(Context context, BigDataConfig config) {
        globalcontext = context;
        BigDataPreference.init(context.getApplicationContext());
        BigDataConstants.init(context.getApplicationContext(), config);
        mThread = new BigDataThread();
        mThread.setName("bigdata-stats-thread");
        mThread.setPriority(Thread.NORM_PRIORITY - 1);
        mThread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable ex) {
                ex.printStackTrace();
            }
        });
        mThread.start();
        mThread.post(new Runnable() {

            @Override
            public void run() {
                LogUtils.i("BigData is ready for launch!");
            }
        });
    }

    public static void postEnv() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Date d = new Date();
        String date = format.format(d);
        ;
        BigDataPreference.getInstance().putString(BigDataPreference.ENV_REPORT_DATE, date);
        post(new BigDataEnvTask());
    }

    public static void postEnvOnExit() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Date d = new Date();
        String date = format.format(d);
        if (!TextUtils.equals(BigDataPreference.getInstance().getString(BigDataPreference.ENV_REPORT_DATE), date)) {
            post(new BigDataEnvTask());
            BigDataPreference.getInstance().putString(BigDataPreference.ENV_REPORT_DATE, date);
        }
    }

    public static void post(BigDataBaseTask task) {
        mThread.post(task);
    }

    public static Context getcontext() {
        return globalcontext;
    }
}
